package com.cloud.template.base.util;

import javax.servlet.http.HttpServletRequest;

/**
 * Title: IP操作工具类
 * Description:  
 * Copyright: Copyright (c)2010
 * Company: hkrt
 * @author haiyang.hu
 */

public class IpUtil {

	public static String getRemortIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}

	/**
	 * 验证SourceIP是否与strIP相匹配，strIP可以包含通配符 SourceIP必须为规则ip地址
	 * @param SourceIP
	 * @param strIP
	 * @return
	 */
	public static boolean validIPForm(String SourceIP, String strIP) {

		String[] arr_Source = SourceIP.split("\\.");
		String[] arr_str = strIP.split("\\.");

		for (int i = 0; i < arr_Source.length; i++) {
			if ((!arr_str[i].equals("*"))
					&& (!arr_Source[i].equals(arr_str[i]))) {
				return false;
			}
		}

		return true;
	}

	/**
	 *  验证SourceIP是否在某个IP地址范围之间(StartIP,EndIP)
	 * @param SourceIP
	 * @param StartIP
	 * @param EndIP
	 * @return
	 */
	public static boolean validIPRange(String SourceIP, String StartIP,
                                       String EndIP) {
		if (compareIP(SourceIP, StartIP) >= 1
				&& compareIP(EndIP, SourceIP) >= 1) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 比较两个IP地址的大小（IPV4，不能包含通配符） 若strIP1或strIP2不符合ip规则，返回-1 strIP1小于strIP2：则返回0;
	 * strIP1等于strIP2：则返回1; strIP1大于strIP2：则返回2;
	 * @param strIP1
	 * @param strIP2
	 * @return
	 */
	public static int compareIP(String strIP1, String strIP2) {

		String[] arr1 = strIP1.split("\\.");
		String[] arr2 = strIP2.split("\\.");

		for (int i = 0; i < arr1.length; i++) {
			int a1 = Integer.parseInt(arr1[i]);
			int a2 = Integer.parseInt(arr2[i]);
			if (a1 > a2) {
				return 2;
			} else if (a1 < a2) {
				return 0;
			}
		}

		return 1;
	}

	/**
	 * 验证SourceIP是否匹配ips SourceIP必须为规则ip地址
	 * @param sourceIP
	 * @param sourceIpUrlIp
	 * @return
	 */
	public static boolean validIP(String sourceIP, String[] sourceIpUrlIp) {

		for (String ip : sourceIpUrlIp) {
			String[] arr_ip = ip.split("-");

			if (arr_ip.length == 2) {
				String StartIP = arr_ip[0].trim();
				String EndIP = arr_ip[1].trim();
				if (validIPRange(sourceIP, StartIP, EndIP)) {
					return true;
				}
			} else {
				String strIP = arr_ip[0].trim();
				if (validIPForm(sourceIP, strIP)) {
					return true;
				}
			}
		}

		return false;
	}
}
